package net.zhengxinyun.performance.service.examNew;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.dto.examDTO.ExamDTO;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.entity.exam.DeptPaperEntity;
import net.zhengxinyun.performance.entity.exam.GeneralPaperEntity;
import net.zhengxinyun.performance.entity.exam.QuestionnaireEntity;
import net.zhengxinyun.performance.entity.exam.WorkPaperEntity;
import net.zhengxinyun.performance.filter.exam.QuestionnaireFilter;
import net.zhengxinyun.performance.mapper.examNew.DeptPaperEntityMapper;
import net.zhengxinyun.performance.mapper.examNew.GeneralPaperEntityMapper;
import net.zhengxinyun.performance.mapper.examNew.QuestionnaireEntityMapper;
import net.zhengxinyun.performance.mapper.examNew.WorkPaperEntityMapper;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.exportService.ExcelDtoService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Date: 2020/3/11 18:32
 * 问卷总表的管理
 */
@Service
public class QuestionnaireServiceImpl implements QuestionnaireService {

    @Autowired
    private QuestionnaireEntityMapper quesMapper;

    @Autowired
    private ExcelDtoService excelDtoService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DeptPaperEntityMapper deptMapper;
    @Autowired
    private WorkPaperEntityMapper workMapper;
    @Autowired
    private GeneralPaperEntityMapper generalMapper;


    @Override
    public HashMap<String, Object> questionnaireManage(String option, QuestionnaireFilter filter) {
        QuestionnaireEntity record = new QuestionnaireEntity();
        record.setExamName(filter.getExamName());
        record.setExamType(filter.getExamType());
        record.setId(filter.getQuestionnaireId());
        record.setExamOption(filter.getExamOption());
        record.setExamWeight(filter.getExamWeight());
        switch (option){
            case "del":
                quesMapper.deleteByPrimaryKey(filter.getQuestionnaireId());
            break;
            case "update":

                int i = quesMapper.updateByPrimaryKeySelective(record);
                break;
            case "add":
                record.setId(null);
                record.setCreateUser(filter.getLoginTel());
                quesMapper.insert(record);
                break;
            case "query":
                HashMap <String,Object> ham  = new HashMap<>();
                List<QuestionnaireFilter> lists = quesMapper.selectListQues(filter);
                ham.put("data",lists);
                return ham;
            default:
                return null;



        }
        return null;
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @Override
    public QuestionnaireEntity selectByPrimaryKey(Long id) {
        return quesMapper.selectByPrimaryKey(id);
    }


    /**
     * 生成问卷
     * @param
     * @param questionnaireId
     * @param file
     * @return
     */
    @Override
    public List<ExamDTO> createQuestionnaire( Long questionnaireId, MultipartFile file ) {

        QuestionnaireEntity questionnaireEntity = quesMapper.selectByPrimaryKey(questionnaireId);
        String quesType = questionnaireEntity.getExamType();

        List<ExamDTO> dtos = new ArrayList<>();
        InputStream inputStream = null;
        Workbook wb = null;
        String fileName = file.getOriginalFilename();
        try {
            inputStream = file.getInputStream();

            if(fileName.endsWith("xls"))
            {
                wb = new HSSFWorkbook(inputStream);
            }else if (fileName.endsWith("xlsx"))
            {
                wb = new XSSFWorkbook(inputStream);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Sheet sheet = wb.getSheetAt(0);
        switch (quesType){
            case "DW":

                String[] head = {"序号","题干"};

                String s = excelDtoService.matchExcelHead(sheet, head);
                if(!"ok".equals(s))
                {
                    return null;
                }

                List<DeptPaperEntity> dwList = getDWList(sheet, questionnaireId);
                System.out.println(dwList.size());//执行校验操作；
                dwList= matchDWdept(dwList);
                System.out.println(dwList.size());

                for (DeptPaperEntity entity : dwList) {
                    ExamDTO dto = new ExamDTO();
                    dto.setDepartCode(entity.getDepartCode());
                    dto.setQuestionnaireId(questionnaireId);
                    dto.setRemarks(entity.getRemarks());
                    dto.setSort(entity.getSort());
                    dto.setStatue(entity.getStatue());
                    dto.setStem(entity.getStem());
                    dtos.add(dto);
                }
                break;
            case "GZ":
                String[] head2 = {"序号","题干"};

                String gzhead = excelDtoService.matchExcelHead(sheet, head2);
                if(!"ok".equals(gzhead))
                {
                    return null;
                }
                List<WorkPaperEntity> workLists = getWorkLists(sheet, questionnaireId);
                for (WorkPaperEntity entity : workLists) {
                    ExamDTO dto = new ExamDTO();
                   // dto.setDepartCode(entity.getDepartCode());
                    dto.setQuestionnaireId(questionnaireId);
                    dto.setRemarks(entity.getRemarks());
                    dto.setSort(entity.getSort());
                    dto.setStatue(1);
                    dto.setStem(entity.getStem());
                    dtos.add(dto);
                }
                break;
            case "YB":
                String[] head3 ={"序号",	"题干",	"选项A",	"选项B",	"选项C",	"选项D",	"选项E","选项F",	 "选项A权重",
                        "选项B权重",	 "选项C权重",	 "选项D权重",	 "选项E权重",	 "选项F权重"};
                String yibanheadm = excelDtoService.matchExcelHead(sheet, head3);
                if(!"ok".equals(yibanheadm))
                {
                    return null;
                }
                List<GeneralPaperEntity> generalPaperEntities = generalPaperEntityList(sheet, questionnaireId);
                for (GeneralPaperEntity entity : generalPaperEntities) {
                    ExamDTO dto = new ExamDTO();
                    // dto.setDepartCode(entity.getDepartCode());
                    dto.setQuestionnaireId(questionnaireId);
                    dto.setRemarks(entity.getRemarks());
                    dto.setSort(entity.getSort());
                    dto.setStatue(1);
                    dto.setStem(entity.getStem());
                    dto.setOpA(entity.getOpA());
                    dto.setOpB(entity.getOpB());
                    dto.setOpC(entity.getOpC());
                    dto.setOpD(entity.getOpD());
                    dto.setOpE(entity.getOpE());
                    dto.setOpF(entity.getOpF());
                    dto.setWgA(entity.getWgA());
                    dto.setWgB(entity.getWgB());
                    dto.setWgC(entity.getWgC());
                    dto.setWgD(entity.getWgD());
                    dto.setWgE(entity.getWgE());
                    dto.setWgF(entity.getWgF());
                    dtos.add(dto);
                }


                break;
            default:
               return null;
        }
        return dtos;
    }

    /**
     * 处理 单位问卷Excel
     * @param sheet
     * @param questionnaireId
     * @return
     */
    List<DeptPaperEntity> getDWList(Sheet sheet ,Long questionnaireId){
        int lastRow =  sheet.getPhysicalNumberOfRows();
        List<DeptPaperEntity> list = new ArrayList<>();
        for (int i = 1; i < lastRow; i++) {
            Row row  = sheet.getRow(i);
            DeptPaperEntity entity = new DeptPaperEntity();

            Cell cell = row.getCell(0);
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);
            int sort = (int) cell.getNumericCellValue();
            entity.setSort(sort);  //设置序号

            Cell cell1 = row.getCell(1);
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            String quesItem = cell1.getStringCellValue();
            entity.setStem(quesItem);

            entity.setQuestionnaireId(questionnaireId);
            list.add(entity);
        }

        return list;

    }

    /**
     * 匹配 单位问卷 中题干（单位）
     * @return
     */
    List<DeptPaperEntity> matchDWdept(List<DeptPaperEntity> list){

        /*
         * 匹配单位
         */
        for (DeptPaperEntity entity : list) {

            String stem = entity.getStem();

            DepartmentEntity departByName = departmentService.getDepartByName(stem);
            if (ObjectUtils.isBlank(departByName)) {
                entity.setRemarks("没有匹配到单位，请修改后重新重新操作");

            }else {
                entity.setRemarks("已匹配单位："+departByName.getDepartAddr());
                entity.setDepartCode(departByName.getDepartcode());
                entity.setStatue(1);
            }



        }

        return list;
    }

    /**
     * 工作问卷处理
     * @param sheet
     * @param questionnareId
     * @return
     */
    List<WorkPaperEntity> getWorkLists(Sheet sheet,Long questionnareId){
        int lastRow =  sheet.getPhysicalNumberOfRows();
        List<WorkPaperEntity> list = new ArrayList<>();
        for (int i = 1; i < lastRow; i++) {
            Row row  = sheet.getRow(i);
            WorkPaperEntity entity = new WorkPaperEntity();

            Cell cell = row.getCell(0);
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);
            int sort = (int) cell.getNumericCellValue();
            entity.setSort(sort);  //设置序号

            Cell cell1 = row.getCell(1);
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            String quesItem = cell1.getStringCellValue();
            entity.setStem(quesItem);

            entity.setQuestionnaireId(questionnareId);
            list.add(entity);
        }
        return  list;
    }


    /**
     * 一般问卷处理数据；
     *
     */
    List<GeneralPaperEntity> generalPaperEntityList(Sheet sheet,Long questionnaireId)
    {

        int lastRow =  sheet.getPhysicalNumberOfRows();
        List<GeneralPaperEntity> list = new ArrayList<>();
        for (int i = 1; i < lastRow; i++) {
            Row row  = sheet.getRow(i);
            GeneralPaperEntity entity = new GeneralPaperEntity();

            Cell cell = row.getCell(0);
            cell.setCellType(Cell.CELL_TYPE_NUMERIC);
            int sort = (int) cell.getNumericCellValue();
            entity.setSort(sort);  //设置序号

            Cell cell1 = row.getCell(1);
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            String quesItem = cell1.getStringCellValue();
            entity.setStem(quesItem);


            Cell cell2 = row.getCell(2);
            cell2.setCellType(Cell.CELL_TYPE_STRING);
            String opA= cell2.getStringCellValue();
            entity.setOpA(opA);

            Cell cell3 = row.getCell(3);
            cell3.setCellType(Cell.CELL_TYPE_STRING);
            String opB= cell3.getStringCellValue();
            entity.setOpB(opB);

            Cell cell4 = row.getCell(4);
            cell4.setCellType(Cell.CELL_TYPE_STRING);
            String opC= cell4.getStringCellValue();
            entity.setOpC(opC);

            Cell cell5 = row.getCell(5);
            cell5.setCellType(Cell.CELL_TYPE_STRING);
            String opD= cell5.getStringCellValue();
            entity.setOpD(opD);


            Cell cell6 = row.getCell(6);
            cell6.setCellType(Cell.CELL_TYPE_STRING);
            String opE= cell6.getStringCellValue();
            entity.setOpE(opE);


            Cell cell7 = row.getCell(7);
            cell7.setCellType(Cell.CELL_TYPE_STRING);
            String opF= cell7.getStringCellValue();
            entity.setOpF(opF);

            Cell cell8 = row.getCell(8);
            cell8.setCellType(Cell.CELL_TYPE_STRING);
            String wgA= cell8.getStringCellValue();
            entity.setWgA(wgA);


            Cell cell9 = row.getCell(9);
            cell9.setCellType(Cell.CELL_TYPE_STRING);
            String wgB= cell9.getStringCellValue();
            entity.setWgB(wgB);


            Cell cell10 = row.getCell(10);
            cell10.setCellType(Cell.CELL_TYPE_STRING);
            String wgC= cell10.getStringCellValue();
            entity.setWgC(wgC);


            Cell cell11 = row.getCell(11);
            cell11.setCellType(Cell.CELL_TYPE_STRING);
            String wgD= cell11.getStringCellValue();
            entity.setWgC(wgD);

            Cell cell12 = row.getCell(12);
            cell12.setCellType(Cell.CELL_TYPE_STRING);
            String wgE= cell12.getStringCellValue();
            entity.setWgE(wgE);


            Cell cell13 = row.getCell(13);
            cell13.setCellType(Cell.CELL_TYPE_STRING);
            String wgF= cell13.getStringCellValue();
            entity.setWgF(wgF);

            entity.setQuestionnaireId(questionnaireId);
            list.add(entity);
        }
        return  list;
    }

    /**
     * 保存问卷
     * @param questionType
     * @param list
     * @return
     */
    @Override
    public int saveExams(String questionType, List<ExamDTO> list) {

        int i=0;
        switch (questionType){
            default:
                return -1;
            case "DW":
                List<DeptPaperEntity> depts = new ArrayList<>();
                for (ExamDTO dto : list) {
                    DeptPaperEntity entity = new DeptPaperEntity();
                    entity.setDepartCode(dto.getDepartCode());
                    entity.setStem(dto.getStem());
                    entity.setQuestionnaireId(dto.getQuestionnaireId());
                    entity.setSort(dto.getSort());
                    depts.add(entity);
                }
                //执行保存操作；
                //deptMapper.insert(depts.get(0)) ;
                i = deptMapper.batchSaves(depts);

                break;
            case "GZ":
                List<WorkPaperEntity> works = new ArrayList<>();
                for (ExamDTO dto : list) {
                    WorkPaperEntity entity = new WorkPaperEntity();
                   // entity.setDepartCode(dto.getDepartCode());
                    entity.setStem(dto.getStem());
                    entity.setQuestionnaireId(dto.getQuestionnaireId());
                    entity.setSort(dto.getSort());
                    works.add(entity);
                }
                //执行保存操作操作
                 i = workMapper.batchSaves(works);
                break;
            case "YB":
                List<GeneralPaperEntity> Generals = new ArrayList<>();
                for (ExamDTO dto : list) {
                    GeneralPaperEntity entity = new GeneralPaperEntity();
                    // entity.setDepartCode(dto.getDepartCode());
                    BeanUtils.copyProperties(dto,entity);
                    entity.setId(null);
                    Generals.add(entity);
                }
                //执行保存操作
                i  = generalMapper.batchSaves(Generals);
                break;

        }
        //生成问卷后改变总表的状态
        Long questionnaireId = list.get(0).getQuestionnaireId();
        if(i>1){
            QuestionnaireEntity record = new QuestionnaireEntity();
            record.setId(questionnaireId);
            record.setIsExist(1);
            quesMapper.updateByPrimaryKeySelective(record);

        }

        return i;
    }
}
